#include <math.h>
#include "Ghost.h"
#include "include.h"
#include "Material.h"
Ghost::Ghost(TextureManager * textureManager,Vector2D position, double lifeTime)
: Object( textureManager,
			new Material("ghost",0,0,false,0.1666667,-1),
			0.0,
			position, 
			Vector2D(0,0),
			Vector2D(0,0),
			NULL,
			0,
			0.0,
			0.0,
			0.0,
			1.0,
			false)
{
	this->lifeTime = lifeTime;
	this->totalLifeTime = lifeTime;
	
	if(textureManager)
	{
		if(!textureManager->LoadTexture(GHOST_TEXTURE))
				printf("Loading %s failed!", GHOST_TEXTURE);
	
		material->SetTextureIndex(textureManager->TextureIndex(GHOST_TEXTURE));
	}
	objectId = GHOST_OBJECT_CLASS;
	
	int * frameSequence = (int *)malloc(sizeof(int)*4);
	frameSequence[0] = 0;
	frameSequence[1] = 1;
	frameSequence[2] = 2;
	frameSequence[3] = 3;
	animationManager = new AnimationManager(0.05, frameSequence, 4, 2, 2);
	
	vertices = (Vector2D*)malloc(sizeof(Vector2D) * 4);
	vertices[0] = Vector2D(-4,5);
	vertices[1] = Vector2D(4,5);
	vertices[2] = Vector2D(4,-5);
	vertices[3] = Vector2D(-4,-5);
	
	numVertices = 4;
	
	CalculateMomentOfInertia();
	//CalculateTextureVertices(0.0);
}
Ghost::~Ghost()
{
	if(animationManager)
		delete(animationManager);
	animationManager = NULL;
}
void Ghost::AddGravity()
{
	float theta = lifeTime * 4 * 3.14159;
	Vector2D dir = Vector2D(cos(theta), 0.1);
	Vector2D gravitationalForce = dir * GRAVITATIONAL_FORCE * mass * -0.5;///(float)numVertices;
	AddForce(gravitationalForce);
}
bool Ghost::PreThinkEntryPoint(double elapsedTime)
{
	lifeTime -= elapsedTime;
	animationManager->AddElapsedTime(elapsedTime);
	if(lifeTime < 0.0)
	{
		objectToDestroy = this;
		return true;
	}
	return false;
}

bool Ghost::PreDrawEntryPoint()
{
	textureVertices = animationManager->GetVertices();
	glEnable(GL_BLEND);
	float alpha = lifeTime/totalLifeTime - 0.5;
	if(alpha < 0)
		alpha = 0;
	glColor4f(1,1,1, alpha);
	glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
	return false;
}
void Ghost::DrawEntryPoint()
{
	if(textureVertices)
	{
		delete(textureVertices);
		textureVertices = NULL;
	}
}
